using System;
using System.Web.Routing;
using System.Web;
using System.Net;
using System.Xml.Linq;
using System.Xml;

using System.Collections.Generic;

namespace Odp.DataServices 
{
    public class sqlServiceDocumentHttpHandler : sqlTableStorageHttpHandlerBase, IHttpHandler
    {
        public string OgdiAlias { get; set; }        

        private const string START_SERVICEDOCUMENT_TEMPLATE =
@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
<service xml:base='{0}' xmlns:atom='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns='http://www.w3.org/2007/app'>
	<workspace>
		<atom:title>Default</atom:title>
";
				//sl-king: most of the properties (only title original OGDI) were added for minimum interactive sdk mvc compatibility
        private const string COLLECTION_TEMPLATE =
@"    <collection href='{0}'>
				<atom:title>{0}</atom:title>
			</collection>
";

        private const string END_SERVICEDOCUMENT_TEMPLATE =
@"	</workspace>
</service>";

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        string MakeValidString(string value)
				{
					if(value != null)
						return value;
					else
						return "";
				}
			
				public void ProcessRequest(HttpContext context)
        {
            if (!this.IsHttpGet(context))
            {
                this.RespondForbidden(context);
            }
            else
            {
							if(OgdiAlias.ToLower() != "sql")
							{
								context.Response.Write("Endpoint '"+OgdiAlias+"' does not exist.");
								context.Response.StatusCode = 404;//internal server error (int)response.StatusCode;
								context.Response.End();
								return;
							}

							//context.Response.Headers["DataServiceVersion"] = "1.0;";
							context.Response.AddHeader("DataServiceVersion","1.0;");
							context.Response.CacheControl = "no-cache";
              context.Response.ContentType = "application/xml;charset=utf-8";

              var xmlBase = "http://" + context.Request.Url.Host + context.Request.Url.AbsolutePath;

							//var accountName = AppSettings.EnabledStorageAccounts[this.OgdiAlias].storageaccountname;
							//var accountKey = AppSettings.EnabledStorageAccounts[this.OgdiAlias].storageaccountkey;

							//var requestUrl = AppSettings.TableStorageBaseUrl + "TableMetadata";
							//WebRequest request = this.CreateTableStorageSignedRequest(context, accountName, accountKey,
							//                                                          requestUrl, false);

              try
              {
								//var response = request.GetResponse();
								//var responseStream = response.GetResponseStream();

								//string _remainder = requestContext.RouteData.Values["remainder"] as string;
								//string _ogdiAlias = context.RouteData.Values["OgdiAlias"] as string;
								//string _entitySet = requestContext.RouteData.Values["EntitySet"] as string;

								var sql = sqlServerConnection.GetDataServiceInstance();
								var reader = sql.GetReader(
									@"SELECT EntitysetName FROM odpdataservicemetadata;");
								//var tables = sql.GetTables();
                context.Response.Write(string.Format(START_SERVICEDOCUMENT_TEMPLATE, xmlBase));
								while(reader.Read())
								{
                  context.Response.Write(string.Format(COLLECTION_TEMPLATE, reader["EntitysetName"].ToString()));
								}
								sql.Close();
                context.Response.Write(END_SERVICEDOCUMENT_TEMPLATE);

								//var feed = XElement.Load(XmlReader.Create(responseStream));


								//var propertiesElements = feed.Elements(_nsAtom + "entry").Elements(_nsAtom + "content").Elements(_nsm + "properties");

								//foreach (var e in propertiesElements)
								//foreach (var table in tables)
								//{
								//  context.Response.Write(string.Format(COLLECTION_TEMPLATE, table, new Guid(table.GetHashCode(),0,0,0,0,0,0,0,0,0,0).ToString()));//najbolj osnovni guid
								//}
								//context.Response.Write(string.Format(COLLECTION_TEMPLATE, "NONEXISTANT", new Guid("NONEXISTANT".GetHashCode(),0,0,0,0,0,0,0,0,0,0).ToString()));//najbolj osnovni guid
                
              }
              catch (Exception ex)
              {
								context.Response.Write(ex.Message);
								context.Response.StatusCode = 500;//internal server error (int)response.StatusCode;
                context.Response.End();
              }
            }
        }

        #endregion
    }
}
